import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 验证SimpleDateFormat方法是线程不安全的
 */
public class Test {

    public static void main(String[] args) {
        testParse();
        testFormat();
    }

    private static void testParse() {
        SimpleDateFormat format =new SimpleDateFormat("yyyyMMdd");

        Runnable run = () -> {
                for(int i=0;i<1000;i++){
                    try {
                        Date date=format.parse("20180627");
                        System.out.println(Thread.currentThread().getName()+"--{"+i+"}--"+date.getTime());
                    } catch (ParseException e) {
                        System.err.println(Thread.currentThread().getName()+"--{"+i+"}--");
                        e.printStackTrace();
                    }
                }
        };

        for (int i = 0; i < 10; i++) {

            Thread t = new Thread(run);
            t.start();
        }
    }


    public static void testFormat() {
        class DateThread extends Thread{
            private Date date;
            private SimpleDateFormat format;
            private String dstr;

            public DateThread(Date date, SimpleDateFormat format, String dstr) {
                this.date = date;
                this.format = format;
                this.dstr = dstr;
            }

            @Override
            public void run() {
                for(int i=0;i<100;i++){
                    String  d =format.format(date);
                    if(!dstr.equals(d)){
                        System.out.println(Thread.currentThread().getName()+"--{"+i+"}--"+d+"--"+dstr);
                    }
                }
            }
        }

        SimpleDateFormat format =new SimpleDateFormat("yyyyMMdd");

        SimpleDateFormat parse =new SimpleDateFormat("yyyyMMdd");
        String d1= "20170707",d2="20180808",d3="20190909",d4="20200101";

        try {
            Thread t1 = new  DateThread(parse.parse(d1),format,d1);
            Thread t2 = new  DateThread(parse.parse(d2),format,d2);
            Thread t3 = new  DateThread(parse.parse(d3),format,d3);
            Thread t4 = new  DateThread(parse.parse(d4),format,d4);
            t1.start();
            t2.start();
            t3.start();
            t4.start();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
